import { Router } from 'express';
import { body } from 'express-validator';
import validateFormData from '../helpers/validate_form.js';
import DB from '../models/db.js';
import { sendHtmlEmail } from '../helpers/email_util.js';
import crypto from 'crypto';

const router = Router();

/**
 * Route to list employer applications records
 * @GET /employerapplications/index/{fieldname}/{fieldvalue}
 */
router.get(['/', '/index/:fieldname?/:fieldvalue?'], async (req, res) => {  
    try {
        const query = {};
        let queryFilters = [];
        let where = {};
        let replacements = {};
        let fieldName = req.params.fieldname;
        let fieldValue = req.params.fieldvalue;
        
        if (fieldName) {
            queryFilters.push(DB.filterBy(fieldName, fieldValue));
        }
        let search = req.query.search;
        if(search) {
            let searchFields = DB.EmployerApplications.searchFields();
            where[DB.op.or] = searchFields;
            replacements.search = `%${search}%`;
        }

        // 根据用户角色过滤数据
        let allowedRoles = ["admin", "eduadmin"];
        let userRole = req.userRoleName;
        if(!allowedRoles.includes(userRole)) {
            if(userRole === 'reviewer') {
                where['reviewer_id'] = req.user.user_id;
            }
        }

        if(queryFilters.length) {
            where[DB.op.and] = queryFilters;
        }

        query.raw = true;
        query.where = where;
        query.replacements = replacements;
        query.order = DB.getOrderBy(req, 'application_id', 'desc');
        query.attributes = DB.EmployerApplications.listFields();
        
        // 添加与 users 表的关联查询
        query.include = [{
            model: DB.Users,
            as: 'reviewer',
            attributes: ['name'],
            required: false
        }];

        let page = parseInt(req.query.page) || 1;
        let limit = parseInt(req.query.limit) || 10;
        let result = await DB.EmployerApplications.paginate(query, page, limit);

        // 处理结果，将审核人姓名添加到每条记录中
        if (result.records) {
            result.records = result.records.map(record => ({
                ...record,
                reviewer_name: record['reviewer.name'] || '未审核'
            }));
        }

        return res.ok(result);
    }
    catch(err) {
        return res.serverError(err);
    }
});

/**
 * Route to view employer application record
 * @GET /employerapplications/view/{recid}
 */
router.get('/view/:recid', async (req, res) => {
    try {
        const recid = req.params.recid || null;
        const query = {}
        const where = {}
        where['application_id'] = recid;
        query.raw = true;
        query.where = where;
        query.attributes = DB.EmployerApplications.viewFields();
        let record = await DB.EmployerApplications.findOne(query);
        if(!record) {
            return res.notFound();
        }
        return res.ok(record);
    }
    catch(err) {
        return res.serverError(err);
    }
});

/**
 * Route to insert employer application record
 * @POST /employerapplications/add
 */
router.post('/add/', 
    [
        body('company_name').not().isEmpty().withMessage('公司名称不能为空'),
        body('business_license').not().isEmpty().withMessage('营业执照号不能为空'),
        body('contact_person').not().isEmpty().withMessage('联系人不能为空'),
        body('contact_phone').not().isEmpty().withMessage('联系电话不能为空'),
        body('contact_email').not().isEmpty().isEmail().withMessage('请输入有效的邮箱地址'),
        body('company_address').not().isEmpty().withMessage('公司地址不能为空'),
        body('company_website').optional().isURL().withMessage('请输入有效的网址'),
    ], validateFormData
, async function (req, res) {
    try {
        let modeldata = req.getValidFormData();
        
        // 检查营业执照号是否已存在
        const existingApplication = await DB.EmployerApplications.findOne({
            where: { business_license: modeldata.business_license }
        });

        if (existingApplication) {
            return res.badRequest('该营业执照号已被使用');
        }

        // 设置初始状态为待审核
        modeldata.application_status = 'pending';
        
        // 保存申请记录
        let record = await DB.EmployerApplications.create(modeldata);
        
        return res.ok(record);
    } catch(err) {
        return res.serverError(err);
    }
});

/**
 * Route to get employer application record for edit
 * @GET /employerapplications/edit/{recid}
 */
router.get('/edit/:recid', async (req, res) => {
    try {
        const recid = req.params.recid;
        const query = {};
        const where = {};
        where['application_id'] = recid;
        query.raw = true;
        query.where = where;
        query.attributes = DB.EmployerApplications.editFields();
        let record = await DB.EmployerApplications.findOne(query);
        if(!record) {
            return res.notFound();
        }
        return res.ok(record);
    }
    catch(err) {
        return res.serverError(err);
    }
});

/**
 * Route to update employer application record
 * @POST /employerapplications/edit/{recid}
 */
router.post('/edit/:recid', 
    [
        body('application_status').optional({nullable: true}).isIn(['pending', 'approved', 'rejected'])
            .withMessage('状态只能是 pending、approved 或 rejected'),
        body('review_notes').optional({nullable: true}),
    ], validateFormData
, async (req, res) => {
    try {
        const recid = req.params.recid;
        let modeldata = req.getValidFormData({ includeOptionals: true });
        
        const query = {};
        const where = {};
        where['application_id'] = recid;
        query.raw = true;
        query.where = where;
        
        let record = await DB.EmployerApplications.findOne(query);
        if(!record) {
            return res.notFound();
        }

        // 如果是审核操作，添加审核人和审核时间
        if (modeldata.application_status && modeldata.application_status !== 'pending') {
            modeldata.reviewer_id = req.user.user_id;
            modeldata.review_time = new Date();

            // 如果申请通过，生成API密钥
            let apiKeyInfo = null;
            if (modeldata.application_status === 'approved') {
                // 生成API密钥和密钥
                const apiKey = crypto.randomBytes(32).toString('hex');
                const apiSecret = crypto.randomBytes(64).toString('hex');

                // 创建API密钥记录
                apiKeyInfo = await DB.ApiKeys.create({
                    employer_id: recid,
                    api_key: apiKey,
                    api_secret: apiSecret,
                    name: `${record.company_name} - 默认密钥`,
                    description: '系统自动生成的默认API密钥',
                    status: 'active'
                });
            }

            // 准备邮件内容
            const statusText = modeldata.application_status === 'approved' ? '通过' : '拒绝';
            const htmlContent = `
                <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
                    <h2 style="color: #333;">雇主申请审核结果通知</h2>
                    <p>尊敬的 ${record.company_name} 负责人：</p>
                    <p>您的申请已审核完成。</p>
                    <p><strong>审核结果：</strong>${statusText}</p>
                    ${modeldata.review_notes ? `<p><strong>审核意见：</strong>${modeldata.review_notes}</p>` : ''}
                    ${apiKeyInfo ? `
                    <p><strong>API密钥信息：</strong></p>
                    <p>API Key: ${apiKeyInfo.api_key}</p>
                    <p>API Secret: ${apiKeyInfo.api_secret}</p>
                    <p style="color: #ff0000;">请妥善保管您的API密钥信息，这是您访问API的唯一凭证。</p>
                    ` : ''}
                    <p>如有任何疑问，请联系管理员。</p>
                    <p>此致</p>
                    <p>系统管理员</p>
                </div>
            `;

            // 发送邮件通知
            try {
                await sendHtmlEmail(
                    record.contact_email,
                    `雇主申请审核结果通知 - ${statusText}`,
                    htmlContent
                );
            } catch (emailError) {
                console.error('发送邮件通知失败:', emailError);
                // 邮件发送失败不影响审核流程
            }
        }
        
        // 更新记录
        await DB.EmployerApplications.update(modeldata, {where: where});
        
        // 获取更新后的记录
        record = await DB.EmployerApplications.findOne({
            where: where,
            include: [{
                model: DB.Users,
                as: 'reviewer',
                attributes: ['name', 'username'],
                required: false
            }],
            raw: true
        });

        // 返回更新后的记录
        return res.ok({
            ...record,
            reviewer_name: record['reviewer.name'] || '未审核',
            reviewer_id: record['reviewer.username'],
            success: true
        });
    }
    catch(err) {
        console.error('更新申请状态时出错:', err);
        return res.serverError(err);
    }
});

/**
 * Route to delete employer application record
 * @GET /employerapplications/delete/{recid}
 */
router.get('/delete/:recid', async (req, res) => {
    try {
        const recid = (req.params.recid || '').split(',');
        const query = {};
        const where = {};
        where['application_id'] = recid;
        query.raw = true;
        query.where = where;
        
        // 检查是否有相关的API密钥
        const apiKeys = await DB.ApiKeys.findAll({
            where: { employer_id: recid }
        });
        
        if (apiKeys.length > 0) {
            return res.badRequest('无法删除：该申请已关联API密钥，请先删除相关API密钥');
        }
        
        await DB.EmployerApplications.destroy(query);
        return res.ok(recid);
    }
    catch(err) {
        return res.serverError(err);
    }
});

export default router; 